package com.hp.springbootwebflux.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author dongxing
 **/
@RestController
@Slf4j
public class TestController {


    @GetMapping(value = "/1")
    public String show() {
        log.info("gen1 start");
        String str = createStr();

        log.info("gen1 end!");
        return str;

    }

    private static String createStr() {

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "do some";
    }

    @GetMapping("/2")
    public Mono<String> show1() {
        log.info("gen2 start!");
        Mono<String> str = Mono.fromSupplier(TestController::createStr);
        log.info("gen2 end!");
        return str;
    }


    /**
     * 返回0-n个元素
     *
     * @return
     */
    @GetMapping(value = "/3",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> show3() {
        log.info("gen3 start!");
        Flux<String> flux = Flux.fromStream(IntStream.rangeClosed(1, 5).mapToObj(i ->
                {
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return "flux data ----" + i;
                }
        ));
        log.info("gen3 end!");
        return flux;
    }

}
